<template>
  <div id="chat-person">
    <van-sticky>
      <van-nav-bar :title="currentSession.username"  left-arrow @click-left="leftClick" @click-right="rightClick" style="background-color:#f6f7f9;">
        <template #right>
          <van-icon name="ellipsis" size="18" />
        </template>
      </van-nav-bar>
    </van-sticky>
    <div class="message" v-scroll-bottom="sessions">
      <div class="private-chat" v-if="currentSession&&currentSession.userAccount != '群聊'">
        <ul >
  		    <li v-for="(entry,index) in sessions[currentUser.userAccount+'#'+currentSession.userAccount]">
            <div class="chatTime">
              <van-tag round text-color="#9a9b9f" color="#fdfffe" size="medium">{{entry.date}}</van-tag>
  		    	</div>
  		    	<div class="main" :class="{selfMain:entry.self}">
  		    		<van-image
                v-if="!entry.self"
                :class="{friendImage:entry.self}"
                round
                width="2.5rem"
                height="2.5rem"
                fit="cover"
                :src="entry.self ? currentUser.avatarUrl: currentSession.avatarUrl"
              />
  		    		<div class="text" :class="{selfText:entry.self}">{{entry.content}}</div>
              <van-image
                v-if="entry.self"
                :class="{selfImage:entry.self}"
                round
                width="2.5rem"
                height="2.5rem"
                fit="cover"
                :src="entry.self ? currentUser.avatarUrl: currentSession.avatarUrl"
              />
  		    	</div>
  		    </li>
          <li>
            <!-- <div class="chatTime">
              <van-tag round text-color="#9a9b9f" color="#fdfffe" size="medium">2023.4.5</van-tag>
  		    	</div> -->
  		    	<div class="main" :class="{selfMain:true}">
  		    		<van-image
                :class="{friendImage:true}"
                round
                width="2.5rem"
                height="2.5rem"
                fit="cover"
                src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"
              />
  		    	  <div class="text" :class="{selfText:true}">哈哈哈</div>
              <van-image
                :class="{selfImage:true}"
                round
                width="2.5rem"
                height="2.5rem"
                fit="cover"
                src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"
              />
            </div>
          </li>
  	    </ul>
      </div>
      <div class="group-chat">
      </div>
    </div>
    <div class="userText">
      <van-cell-group inset>
        <van-field
          v-model="sentMessage.content"
          rows="1"
          autosize
          type="textarea"
          placeholder="请输入聊天内容...."
        >
          <template #button>
            <van-button 
              class="submit"
              size="small" 
              color="#3286A0 "
              plain
              @click="submitMessage"
            >
              发送
            </van-button>
          </template>
        </van-field>
      </van-cell-group>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, computed, watch, nextTick} from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from '@/store';
//
const store = useStore();

onMounted(() => {
  store.dispatch('connect');
})


const router = useRouter();
const leftClick = () => {
  router.back();
}
const rightClick = () => {
  alert('右边');
}

//在 <script setup> 中，任何以 v 开头的驼峰式命名的变量都可以被用作一个自定义指令
//自动滑动到底部
const vScrollBottom = {
  mounted: (el) => {
    setTimeout(function () {
      el.scrollTop+=9999;
    },1)
  }
}

//当前登录用户的信息
const currentUser  = JSON.parse(window.sessionStorage.getItem('user') || '{}');
//当前选中的用户，默认为群聊
const currentSession  = JSON.parse(window.sessionStorage.getItem('currentSession') || '{}');

//与该用户的聊天记录
let sessionsLocal = reactive(JSON.parse(window.localStorage.getItem('sessions') || '[]'))
store.state.socketModule.sessions = sessionsLocal;
const sessions = computed(() => {
  return store.state.socketModule.sessions;
})
console.log('sessions', sessions);

const sentMessage = reactive({
  from: "",
  fromUsername: "",
  to: "",
  content: "",
  messageTypeId: 1
});


//点击发送
const submitMessage = () => {
  // console.log(currentUser)
  //私聊
  sentMessage.from = currentUser.userAccount;
  sentMessage.fromUsername = currentUser.username;
  sentMessage.to = currentSession.userAccount;
  // console.log(sentMessage)
  store.state.socketModule.stomp.send("/ws/chat",{},JSON.stringify(sentMessage));
  //提交私聊消息记录
  store.commit('addMessage',sentMessage);
  //监听存在localStorage数据的变化
  // sessions = JSON.parse(window.localStorage.getItem('sessions') || '[]');
  //清空输入框
  sentMessage.content='';
  //todo 这里是手动刷新页面，应该是刷新组件但是暂时无法做到
  // router.go(0);
  console.log('sessions',sessions)
}

</script>

<style scoped>
#chat-person {
  position: absolute;
	top: 0px;
	left: 0;
  height: 90%;
  width: 100%;
  background-color: #f6f7f9;
}
.message {
  padding: 15px;
	height: 78%;
  max-height: 80%;
  overflow-y: scroll;
	overflow-x: hidden;
  background-color: #f6f7f9;
}
ul {
  list-style-type: none;
	padding-left: 0px;
}
li {
  margin-bottom: 15px;
}
.chatTime {
  text-align: center;
}
.main {
  display: flex;
  align-items: center;
}
.text {
	display: inline-block;
	padding: 0 10px;
  margin-left: 15px;
	max-width: 80%;
	background-color: #ffffff;
  line-height: 44px;
  border-radius: 8px;
}

.selfMain {
  justify-content: end;
}
.friendImage {
  display: none;
}
.selfText {
  margin-right: 15px;
  background-color:#b9e7fe;
}

.userText {
  position:absolute;
  bottom: 0;
  left: 0;
  width: 100%;
}
.submit {
  border: none;
}
</style>